package jman.competition11;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DatebaseManager {
	private Connection con=null;
	private PreparedStatement ps=null;
	private ResultSet rs=null;
	public ResultSet getRs() {
		return rs;
	}
	//创建数据库连接对象
	public boolean getCon(){
		String driver="com.mysql.jdbc.Driver";
		String database="java3";
		String userName="root";
		String pwd="gzy411527";
		String url="jdbc:mysql://localhost:3306/"+database+"??useUnicode=true&characterEncoding=utf-8";
		try {
			Class.forName(driver);
			con=DriverManager.getConnection(url, userName, pwd);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("数据库连接失败");
			con=null;
			return false;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("加载驱动失败");
			return false;
		}
		return true;
	}
	//获取SQL命令的执行对象
	private PreparedStatement getPs(String sql){
		try {
			ps=con.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("获取SQL执行对象失败");
			ps=null;
		}
		return ps;
	}
	//增
	public boolean add(String sql){
		getCon();
		try {
			getPs(sql).execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			return false;
		}
		return true;
	}
	//删
	public boolean delete(String sql){
		getCon();
		try {
			getPs(sql).execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("删除记录失败");
		}		
		return true;
	}
	//改
	public boolean update(String sql){
		getCon();
		try {
			getPs(sql).executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("修改记录失败");
			return false;
		}
		return true;
	}
	//查
	public boolean read(String sql){
		getCon();
		try {
			rs=getPs(sql).executeQuery();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("查询记录失败");
			rs=null;
			return false;
		}
			return true;
	}
	//关闭结果集
	public void closeRs(){
		try {
			if(rs!=null){
				rs.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("关闭结果集失败");
		}
	}
	//关闭SQL执行对象
	public void closePs(){
		try {
			if(ps!=null){
				ps.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("关闭SQL执行对象失败");
		}
	}
	//断开数据库连接
	public void closeCon(){
		try {
			if(con!=null){
				con.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("断开数据库连接失败");
		}
	}
}
